# -*- coding: utf8 -*-

import os
from project.sqlite3_db import dict_factory

class Table( object ):

    _table_name = None
    _db_name = None
    _db_path = "."
    _db = None

    def __init__(self, db_name, db_path="./db"):
        if self._table_name is None:
            raise AttributeError("Define non-empty class variable '_table_name'")
        self._db_name = db_name
        self._db_path = db_path
        pass

    def connect( self ):
        import sqlite3

        db_path = os.path.join(self._db_path, self._db_name, "%s.sqlite3" % self._table_name)
        db_path = os.path.abspath(db_path)

        db_dir = os.path.dirname(db_path)
        if not os.path.exists(db_dir):
            os.makedirs(db_dir)

        self._db = sqlite3.connect(db_path)
        self._db.row_factory = dict_factory
        self.create()
        return

    def clean( self ):

        db_path = os.path.join(self._db_path, self._db_name, "%s.sqlite3" % self._table_name)
        db_path = os.path.abspath(db_path)

        os.unlink(db_path)
        self._db = None

        self.create()

        return

    def close(self):
        if self._db:
            self._db.close()
            self._db = None
        return

    def getConnection(self):
        if self._db is None:
            self.connect()
            cur = self.getCursor()
            cur.execute("PRAGMA temp_store=2")
            cur.execute("PRAGMA synchronous=OFF")
            cur.close()
        return self._db

    def getCursor(self):
        return self.getConnection().cursor()

    def create( self ):
        raise NotImplemented

    pass
